package com.sunseen.capacitormachine.modules.home;

import android.util.Log;
import android.view.View;

import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.commumication.tcp.event.DetectedImplosionEvent;
import com.sunseen.capacitormachine.commumication.tcp.event.HolderTemperatureEvent;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.databinding.FragmentCapacitorListBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.home.adapter.CapacitorItemAdapter;
import com.sunseen.capacitormachine.modules.home.bean.CapacitorAdapterBean;
import com.sunseen.capacitormachine.data.bean.CapacitorBean;
import com.sunseen.capacitormachine.data.bean.HolderBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zest
 */
public class CapacitorListFragment extends BaseFragment {

    private int holderId;
    private int temperature;
    private List<CapacitorBean> capacitorList;

    public void setData(HolderBean holderBean) {
        DataUtil.TapHolderId = holderBean.getHolderId();
        holderId = holderBean.getHolderId();
        capacitorList = new ArrayList<>();
        capacitorList.addAll(holderBean.getCapacitorList());
        //去除头部用于填补间距的空电容
        capacitorList.remove(0);
        this.temperature = holderBean.getTemperature();
    }

    @Override
    protected int setLayout() {
        return R.layout.fragment_capacitor_list;
    }

    private CapacitorItemAdapter adapter;
    private FragmentCapacitorListBinding binding;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        binding = (FragmentCapacitorListBinding) viewDataBinding;
        binding.tvHolderName.setText(String.format(getString(R.string.holder_format), holderId));
        binding.tvTempValue.setText(String.format(getString(R.string.temperature_format), temperature / 10.0f));
        binding.setOnBackClick((view) -> {
            DataUtil.TapHolderId = DataUtil.DEFAULT_ID;
            pop();
        });
        binding.rvCapacitor.setLayoutManager(new GridLayoutManager(getContext(), 5));
        adapter = new CapacitorItemAdapter(R.layout.layout_item_capacitor, getAdapterBean());
        binding.rvCapacitor.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.e("test", "position = " + position);
                CapacitorAdapterBean adapterBean = (CapacitorAdapterBean) adapter.getData().get(position);
                CapacitorDetailFragment fragment = new CapacitorDetailFragment();
                fragment.setData(adapterBean.getUid(), holderId, position, adapterBean.isNormal(), temperature);
                start(fragment);
            }
        });
        binding.tvNormalCapacitorCount.setText(String.format(getString(R.string.capacitor_count_format), errorCount));
        EventBus.getDefault().register(this);
    }

    private int errorCount = 0;

    private List<CapacitorAdapterBean> getAdapterBean() {
        List<CapacitorAdapterBean> list = new ArrayList<>();
        for (int i = 0; i < capacitorList.size(); i++) {
            CapacitorBean capacitorBean = capacitorList.get(i);
            list.add(new CapacitorAdapterBean(capacitorBean.getUid(),
                    capacitorBean.getSequence(), i + 1, capacitorBean.getVoltage(),
                    capacitorBean.getCurrent(), capacitorBean.isEmpty(),
                    capacitorBean.isNormal()));
            if (!capacitorBean.isNormal()) {
                errorCount++;
            }
        }
        return list;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDetectedImplosionEvent(DetectedImplosionEvent event) {
        if (event.getHolderId() == holderId) {
            CapacitorAdapterBean bean = adapter.getData().get(event.getPos());
            if (bean.isNormal()) {
                bean.setNormal(false);
                adapter.notifyItemChanged(event.getPos());
                errorCount++;
                binding.tvNormalCapacitorCount.setText(String.format(getString(R.string.capacitor_count_format), errorCount));
            }
        }
    }

    private int lastTemp = 0;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTemperatureEvent(HolderTemperatureEvent event) {
        if (!hidden && Math.abs(event.getTemperature() - lastTemp) > 1) {
            binding.tvTempValue.setText(String.format(getString(R.string.temperature_format),
                    event.getTemperature() / 10.0f));
            lastTemp = event.getTemperature();
        }
    }

    private boolean hidden = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
